import 'package:dali_ng_pera/mob/dnp_mob.dart';
import 'package:dali_ng_pera/page/certification/dialog/dnp_city_choice_dialog.dart';
import 'package:dali_ng_pera/page/certification/dialog/dnp_single_choice_dialog.dart';
import 'package:dali_ng_pera/page/certification/dialog/dnp_time_choice_dialog.dart';
import 'package:dali_ng_pera/page/certification/model/dnp_from_common_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:ios_keyboard_action/ios_keyboard_action.dart';

import '../../tool/dnp_time_tool.dart';
import '../widget/dnp_app_bar.dart';
import 'controller/dnp_from_common_controller.dart';

class DnpCertificationCommonFromPage extends StatefulWidget {
  final String already;
  final String path;
  final String submitPath;
  final String nervous;
  final String title;

  const DnpCertificationCommonFromPage(
      {super.key,
      required this.already,
      required this.path,
      required this.submitPath,required this.nervous,required this.title});

  @override
  State<DnpCertificationCommonFromPage> createState() =>
      _DnpCertificationCommonFromPageState();
}

class _DnpCertificationCommonFromPageState
    extends State<DnpCertificationCommonFromPage> {
  final controller = Get.put(DnpFromCommonController());
  final _formKey = GlobalKey();
  final _allHeightKey = GlobalKey();
  double spaceHeight = 100;
  int startTime = 0;

  @override
  void initState() {
    super.initState();
    startTime = DnpTimeTool.timestamp;
    controller.onRequestData(widget.path, widget.already);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF53A9FF),
              Color(0xFFDFF1FF),
            ],
          ),
        ),
        child: Listener(
          onPointerDown: (event) {
            SystemChannels.textInput.invokeMethod('TextInput.hide');
          },
          child: Column(
            children: [
              DnpAppBar(title: widget.title),
              Expanded(
                key: _allHeightKey,
                child: Obx(() {
                  final formModel = controller.formModel.value;
                  if (formModel == null || formModel.floor == null) {
                    return Center(child: CircularProgressIndicator());
                  }

                  // 按照 staring 字段排序
                  final sortedFloor = List<DnpFloorModel>.from(formModel.floor!);
                  sortedFloor
                      .sort((a, b) => (a.staring ?? 0).compareTo(b.staring ?? 0));

                  return SingleChildScrollView(
                    child: Column(
                      children: [
                        ...sortedFloor.asMap().entries.map((entry) {
                          final index = entry.key;
                          final item = entry.value;
                          return _buildDynamicFromItem(
                            item,
                            FocusNode(),
                            key: index == 0 ? _formKey : null,
                          );
                        }).toList(),
                      ],
                    ),
                  );
                }),
              ),
              SizedBox(height: 20),
              _buildBottomButton(),
              SizedBox(height: 34),
            ],
          ),
        ),
      ),
    );
  }

  // 动态创建表单项
  Widget _buildDynamicFromItem(DnpFloorModel item, FocusNode focusNode,{Key? key}) {
    final iesous = item.iesous ?? '';
    final fieldController = controller.getController(iesous);

    if (fieldController == null) return SizedBox.shrink();

    // 根据 paper 类型判断是否只读
    bool isReadOnly = false;
    VoidCallback? onTap;

    // brown 为 1 表示是数字输入
    List<TextInputFormatter>? inputFormatters;
    TextInputType? keyboardType;

    if (item.brown == 1) {
      inputFormatters = [FilteringTextInputFormatter.digitsOnly];
      keyboardType = TextInputType.number;
    }

    switch (item.paper) {
      case 'walkeda': // 单选选择器
        isReadOnly = true;
        onTap = () => _showSingleChoiceDialog(item);
        break;
      case 'walkedb': // 文本输入
        isReadOnly = false;
        break;
      case 'walkedc': // 城市选择器
        isReadOnly = true;
        onTap = () => _showCityChoiceDialog(item);
        break;
      default:
        isReadOnly = false;
    }

    return Container(
      key: key,
      margin: EdgeInsets.only(left: 14, right: 14, top: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            item.discernible ?? "Field",
            style: TextStyle(
              fontSize: 16,
              color: Color(0xFF252630),
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 12),
          IOSKeyboardAction(
            focusNode: focusNode,
            backgroundColor:Colors.grey.shade300,
            label: "Done",
            textColor: Colors.blue,
            focusActionType: FocusActionType.done,
            onTap: (){
              FocusScope.of(context).requestFocus(FocusNode());
            },
            child: TextField(
              focusNode: focusNode,
              onTap: onTap,
              controller: fieldController,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w400,
                color: Color(0xFF252630),
              ),
              readOnly: isReadOnly,
              keyboardType: keyboardType,
              inputFormatters: inputFormatters,
              onChanged: (value) {
                controller.updateFormValue(iesous, value);
              },
              decoration: InputDecoration(
                filled: true,
                fillColor: Colors.white,
                hintText: item.wore ?? "Please input",
                hintStyle: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w400,
                  color: Color(0xFFABABAB),
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.transparent,
                    width: 1,
                  ),
                ),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.transparent,
                    width: 1,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide(
                    color: Colors.transparent,
                    width: 2,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildBottomButton() {
    return GestureDetector(
      onTap: () {
        controller.submitForm(widget.already, widget.submitPath,(){
          DnpMob.inexplicable(widget.nervous, startTime, DnpTimeTool.timestamp);
        });
      },
      child: Container(
        width: double.infinity,
        height: 48,
        alignment: Alignment.center,
        margin: EdgeInsets.only(left: 24, right: 24, top: 10),
        decoration: BoxDecoration(
          color: Color(0xFF1D4AC8),
          borderRadius: BorderRadius.all(Radius.circular(16)),
        ),
        child: Text(
          "Next",
          style: TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  // 显示单选对话框
  void _showSingleChoiceDialog(DnpFloorModel item) {
    final iesous = item.iesous ?? '';
    final fieldController = controller.getController(iesous);
    if (fieldController == null) return;

    // 从 usually 列表中提取选项
    final options = item.usually?.map((e) => e.beersheba ?? '').toList() ?? [];
    if (options.isEmpty) return;

    // 获取当前已选中的值
    final currentValue =
        fieldController.text.isNotEmpty ? fieldController.text : null;

    showDialog(
      context: context,
      builder: (context) {
        return DnpSingleChoiceDialog(
          options: options,
          title: item.discernible ?? "",
          selectedOption: currentValue,
          onConfirm: (value) {
            fieldController.text = value;

            // 查找对应的 heard 值（ID）
            final selectedOption = item.usually?.firstWhere(
              (e) => e.beersheba == value,
              orElse: () => DnpUsuallyModel(),
            );
            if (selectedOption?.heard != null) {
              controller.updateFormValue(iesous, selectedOption!.heard);
            }
          },
        );
      },
    );
  }

  // 显示城市选择对话框
  void _showCityChoiceDialog(DnpFloorModel item) {
    final iesous = item.iesous ?? '';
    final fieldController = controller.getController(iesous);
    if (fieldController == null) return;

    showDialog(
      context: context,
      builder: (context) {
        return DnpCityChoiceDialog(
          onConfirm: (value) {
            // 拼接城市字符串，格式：region|province|city
            final cityString =
                "${value.region}|${value.province}|${value.city}";
            fieldController.text = cityString;
            // 存储为字符串，而不是 map 对象
            controller.updateFormValue(iesous, cityString);
          },
        );
      },
    );
  }
}
